<template>
  <ChartContainer :title="title">
    <div class="chart" ref="chartRef"></div>
  </ChartContainer>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, toRefs } from 'vue';
import * as echarts from 'echarts';
import ChartContainer from './ChartContainer.vue';
import { getCategoryDistribution } from '../../api/auth';

defineOptions({
  name: 'RightTop'
});

// 定义类别数据类型
interface CategoryItem {
  name: string;
  value: number;
}

const props = defineProps({
  title: {
    type: String,
    default: '类别数量'
  },
  chartData: {
    type: Array,
    default: () => []
  }
});

const { title, chartData } = toRefs(props);

const chartRef = ref(null);
let chart: echarts.ECharts | null = null;
const localChartData = ref<CategoryItem[]>([]);

const fetchCategoryData = async () => {
  try {
    const res = await getCategoryDistribution();
    if (res.data && res.data.code === 200 && res.data.data) {
      localChartData.value = res.data.data.map((item: any) => ({
        name: item.name,
        value: item.count || 0
      }));
    }
    initChart();
  } catch (error) {
    console.error('获取类别数量数据失败:', error);
    initChart();
  }
};

const getBarColor = (index: number) => {
  const colors = [
    'rgba(169, 112, 193, 0.8)',
    'rgba(255, 166, 41, 0.8)',
    'rgba(60, 191, 127, 0.8)',
    'rgba(247, 92, 93, 0.8)',
    'rgba(69, 165, 255, 0.8)'
  ];
  
  return colors[index % colors.length];
};

const initChart = () => {
  if (!chartRef.value) return;
  
  chart = echarts.init(chartRef.value);
  
  const data: CategoryItem[] = localChartData.value;
  
  if (data.length === 0) {
    if (chart) {
      chart.setOption({
        title: {
          text: '暂无类别数据',
          left: 'center',
          top: 'middle',
          textStyle: {
            color: '#fff',
            fontSize: 16
          }
        }
      });
    }
    return;
  }
  
  const maxValue = Math.max(...data.map(item => item.value));
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '30%',
      right: '12%', 
      bottom: '5%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      show: false,
      type: 'value'
    },
    yAxis: {
      type: 'category',
      inverse: true,
      data: data.map(item => item.name),
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        show: true,
        fontSize: 12,
        color: '#fff',
        margin: 18,
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        barWidth: 16,
        barGap: '30%',
        itemStyle: {
          borderRadius: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5
        },
        label: {
          show: true,
          position: 'right',
          color: '#fff',
          fontSize: 16,
          fontWeight: 'bold'
        },
        data: data.map((item, index) => {
          return {
            value: item.value,
            itemStyle: {
              color: getBarColor(index)
            }
          };
        })
      }
    ]
  };
  
  chart.setOption(option);
};


watch(() => chartData.value, () => {
  if (chart) {
    chart.dispose();
    initChart();
  }
}, { deep: true });

onMounted(() => {
  fetchCategoryData();
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
  }
});

// 添加refresh方法供父组件调用
const refresh = async () => {
  await fetchCategoryData();
};

// 暴露refresh方法
defineExpose({
  refresh
});
</script> 

<style>
.chart {
  width: 100%;
  height: 280px;
  padding: 10px;
  border-radius: 6px;
  animation: chartFadeIn 0.8s ease-in-out;
  display: block !important;
}

@keyframes chartFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 增强图表轴线样式 */
.chart path.domain,
.chart .tick line {
  stroke-opacity: 0.3;
  stroke-width: 1px;
}

/* 图表标题样式增强 */
.chart-title {
  margin-bottom: 15px;
  position: relative;
  text-shadow: 0 0 5px rgba(0, 157, 255, 0.7);
  letter-spacing: 1px;
}

.chart-title::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background: linear-gradient(to right, transparent, rgba(0, 157, 255, 0.8), transparent);
}
</style>